<?php

class AgentAction extends CommonAction
{
	public  function  tongjidata()
	{
		$namelist=$this->userlist();
		$model=new Model();
		$sql = " SELECT sum(money) as tmoney ,DATE_FORMAT(addtime,'%d') as time";
		$sql .=" ,TO_DAYS(NOW())-to_days(addtime) as days,unix_timestamp(addtime) as dayparam ";
		$sql .= " from yst_consumption where username in (".$namelist.") group by TO_DAYS(addtime) order by addtime desc limit 0 ,30";

		$zdata = $model->query($sql);
		$category = "";
		$showdatas = "";
		$template = "{ y:%f,days:'%d' },";
		$showarray = array();
		foreach ($zdata as $k => $v) $showarray[$v["days"]] = $v;
		for ($i = 30; $i > 0; $i--)
		{
			$money = 0;
			$cutetime = time() - $i * 24 * 3600;
			$time = date("Y/m/d", $cutetime);
			$days=0;
			$elemnet = $showarray[$i];
			if (!empty($elemnet))
			{
				$money = $elemnet["tmoney"];
				$days = $elemnet["dayparam"];
			}

			$category .= "'" . $time . "',";
			$showdatas .= sprintf($template, $money, $days);
		}
		$category=substr($category,0,-1);
		$showdatas=substr($showdatas,0,-1);
		$chartdata["category"]=$category;
		$chartdata["showdatas"]=$showdatas;
		return $chartdata;
	}

  //代理商每月新增客户数量
    public function newnumbmonthly(){

        $agentId=$_SESSION['agent']['id'];
         $sql=<<<STR
                select CONVERT(date_format(Regtime,'%c'),SIGNED) as month,count(id)as num from yst_user
                where DATE_FORMAT(Regtime,'%Y')=DATE_FORMAT(now(),'%Y') and ProxyId=$agentId
                group by month
                order by month asc
STR;

       $user=M("user");
       $res=$user->query($sql);
       $monthnum=array();
       foreach($res as $k=>$v){
           $monthnum[$v['month']]=$v['num'];
       }
       for($i=1;$i<13;$i++){
          if(!isset($monthnum["$i"])){
              $monthnum["$i"]="0";
          }
       }
        ksort($monthnum);
        $arr_data=array();
        $json_tml="{y:%d},";
        $json_month='';
        foreach($monthnum as $k=>$v){
            $arr_temp['y']=(int)$v;
            $json_month .= sprintf($json_tml,$arr_temp['y']);
        }
       return trim_kongge($json_month);
    }
	public function userlist(){
		$user=D('User');
		$arr_agent['ProxyId']=$_SESSION["agent"]['id'];
		$userlist=$user->field('Username')->where($arr_agent)->select();
		$usernames=arr2str($userlist);//获取到当前代理上的所有客户
		return $usernames;
	}
	public function user_consumption(){
		/*---------------------统计代理商计费数据----------------------*/
		$consumption=D('Consumption');
		$userstr=$this->userlist();//此处获取当前代理商，所有用户UserName字符串
		/*计算计费数据总额*/
		$condition["username"]=array("exp","in ($userstr)");
		$money['total']=$consumption->where($condition)->sum("money");

		/*计算昨日计费数据*/
		$sql = 'SELECT SUM(money) as yesterdaymoney';
		$sql.= ' FROM yst_consumption ';
		$sql.= " WHERE username in ($userstr)";
		$sql.= ' AND TO_DAYS( NOW( ) ) - TO_DAYS(addtime) = 1';
		$money['yesterday']=$consumption->query($sql);
		$money['yesterday']=$money['yesterday'][0]['yesterdaymoney'];

		/*计算本月计费数据*/
		$sql = 'SELECT SUM(money) as monthmoney';
		$sql.= ' FROM yst_consumption ';
		$sql.= " WHERE username in ($userstr)";
		$sql.= " AND DATE_FORMAT(addtime, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )";
		$money['monthmoney']=$consumption->query($sql);
		$money['month']=$money['monthmoney'][0]['monthmoney'];

        /*计算上月计费数据*/
        $sql = 'SELECT SUM(money) as lastmonth';
        $sql.= ' FROM yst_consumption ';
        $sql.= " WHERE username in ($userstr)";
        $sql.= " AND DATE_FORMAT(addtime, '%Y-%m' ) = DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 1 MONTH),'%Y-%m')";
        $money['lastmonth']=$consumption->query($sql);
        $money['lastmonth']=$money['lastmonth'][0]['lastmonth'];

        /*计算最近7天的平均消费*/
        $sql = 'SELECT SUM(money) as avg';
        $sql.= ' FROM yst_consumption ';
        $sql.= " WHERE username in ($userstr)";
        $sql.= " AND DATE_FORMAT(addtime, '%Y-%m-%d' ) > DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 7 day),'%Y-%m-%d')";
        $money['avg']=$consumption->query($sql);
        $money['avg']=$money['avg'][0]['avg'];
        $money['avg']=$money['avg']/7;
        $money['avg']=sprintf("%.1f",$money['avg']);
		return $money;
	}
	public function user_info(){
		/*---------------------统计代理商客户数据----------------------*/
		$arr_agent['ProxyId']=$_SESSION["agent"]['id'];//获取到代理商ID
        $agentName=$_SESSION['agent']['username'];
		$user=D('User');
		
		/*获取预存款小于1000的客户数量*/
		$arr_agent["Usermoney"]=array("lt",1000);
		$userinfo['not_sufficient']=$user->where($arr_agent)->count();//余额不足客户数量
		array_remove($arr_agent,1);//删除余额不足客户数组条件

		/*获取代理商已经停用的客户数量*/
		$arr_agent["Active"]=array("EQ",0);//0为停用，1为激活
		$userinfo['not_active']=$user->where($arr_agent)->count();//已经停用客户数量
		array_remove($arr_agent,1);//删除已经停用客户数组条件

		/*获取代理商所有用户数量*/
		$userinfo['count_user']=$user->where($arr_agent)->count();//所有客户数量

        /*获取代理商下的所有站点数量*/
         $userNames=$this->userlist();
         array_remove($arr_agent,0);
         $arr_agent['Username']=array("exp","in($userNames)");
         $userinfo['count_site']=M('website')->where($arr_agent)->count();//所有站点数量

        /*获取代理商所有关键词数量*/
        $arr_agent['enyinqing']="baidu";
        $userinfo['count_keyword']=M('keyword')->where($arr_agent)->count();//所有关键词数量


        /*获取代理商账户金额的预计使用天数*/
        $consumeModel = M('consume');
        //平均消费
        $sql="select to_days(now())-to_days(min(addtime)) as days from yst_consume";
        $days=$consumeModel->query($sql);
        $days=$days[0]['days'];
        if($days<7){
            $sql="select sum(money) tmoney from yst_consume where proxyname='".$agentName."'";
            $tmoney=$consumeModel->query($sql);
            $tmoney=$tmoney[0]['tmoney'];
            if($days==0){
                $money['avg']=$tmoney;
            }else{
                $money['avg']=$tmoney/$days;
            }
        }else{
            $sql = 'SELECT SUM(money) as tmoney';
            $sql.= ' FROM yst_consume ';
            $sql.= " WHERE proxyname='".$agentName."'";
            $sql.= " AND DATE_FORMAT(addtime, '%Y-%m-%d' ) > DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 7 day),'%Y-%m-%d')";
            $totalMoney=$consumeModel->query($sql);
            $totalMoney=$totalMoney[0]['tmoney'];
            $money['avg']=$totalMoney/7;
            $money['avg'] = sprintf("%.1f",$money['avg']);
        }
        $condition['id']=$_SESSION["agent"]['id'];
        $yu_e=M('proxy')->where($condition)->getField("money");
        $userinfo['usedays']=$yu_e/ $money['avg'];
        $userinfo['usedays']= floor($userinfo['usedays']);
        return $userinfo;


    }

    //代理商发送消息给客户
    public function broadcast(){
        $agentId=$_SESSION['agent']['id'];
        $this->assign("agentId",$agentId);
        $this->display();
    }

   /* public function publish(){
        $agentName=$_SESSION['agent']['username'];
        $message=M("message");
        $agentModel=M("proxy");

        $data=$message->create();
        if(!$data){
            exit($message->getError());
        }

        $data['creater']=$agentName;
        $type=$data['type'];

        if($type==1){

            $data['receive']="全部用户";

        }else if($type==2){

            $toAgent=I("post.agentId");
            $proxyName=$agentModel->field('username')->find($toAgent);
            $data['receive']=$proxyName['username']."下的所有用户";

        }else if($type==3){

            $toAgent=I("post.agentId");
            $proxyName=$agentModel->field('username')->find($toAgent);
            $toUser=I("post.userid");
            $user=M("user");
            $userName=$user->field('Username')->find($toUser);
            $data['receive']="代理商".$proxyName['username']."下的".$userName['Username']."用户";

        }else{

            $data['type']=4;
            $data['receive']=$agentName."下的所有用户";
        }

        $data['publishtime']=Date("Y-m-d H:i:s");

        $result=$message->add($data);
        if($result){
            $this->success("发布成功");
        }else{
            $this->error("发布失败");
        }
    }*/
    //获取所有的代理商
    public function getagent(){

      $agentId=$_SESSION['agent']['id'];
      if($agentId!=1) $this->error("您没有权限");
        $agentModel=M("proxy");
        $agentlist=$agentModel->field("username")->select();
        $agentName=array();
        foreach($agentlist as $key=>$val){
           $agentName[$key]=$val['username'];
        }
        $agentName['status']='true';
        $ajax=json_encode($agentName);
        echo $ajax;
    }
}